package com.voute.View.Activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Consts.Constants;
import com.voute.Model.Bean.BaseBean;
import com.voute.Model.Bean.RecommendCirclesBean;
import com.voute.Model.Bean.RecommendCirclesEntity;
import com.voute.Model.Bean.UploadImgResponseBean;
import com.voute.Model.IUploadFileModel;
import com.voute.Model.Impl.UploadFileModelImpl;
import com.voute.Presenter.IPublishFeedPresenter;
import com.voute.Presenter.Impl.PublishFeedPresenterImpl;
import com.voute.R;
import com.voute.Utils.CommonSubscriber;
import com.voute.Utils.FileUtils;
import com.voute.Utils.GlideUtils;
import com.voute.Utils.RetrofitUploadFileParameterBuilder;
import com.voute.Utils.TransformUtils;
import com.voute.View.IView.ICreateFeedView;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

/**
 * Created by liucxu on 2017/4/27.
 */

public class CreateFeedActivity extends BaseActivity implements ICreateFeedView {
    @BindView(R.id.back_layout)
    RelativeLayout back_layout;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.publish_tv)
    TextView publish_tv;

    @BindView(R.id.edt_title)
    EditText edt_title;
    @BindView(R.id.edt_circle_name)
    EditText edt_circle_name;
    @BindView(R.id.edt_more)
    EditText edt_more;
    @BindView(R.id.imv_feed_image)
    ImageView imv_feed_image;
    @BindView(R.id.layout_vote_option)
    RelativeLayout layout_vote_option;
    @BindView(R.id.edt_default_positive)
    EditText edt_default_positive;
    @BindView(R.id.edt_default_negative)
    EditText edt_default_negative;
    @BindView(R.id.layout_vs)
    LinearLayout layout_vs;

    @BindView(R.id.radio_group_time_line)
    RadioGroup radio_group_time_line;
    @BindView(R.id.radio_btn_8hour)
    RadioButton radio_btn_8hour;
    @BindView(R.id.radio_btn_24hour)
    RadioButton radio_btn_24hour;
    @BindView(R.id.line_horizontal3)
    View line_horizontal3;
    @BindView(R.id.layout_feed_time_line)
    RelativeLayout layout_feed_time_line;
    @BindView(R.id.layout_recommend)
    RelativeLayout layout_recommend;
    @BindView(R.id.recommend_list_view)
    ListView recommend_list_view;
    @BindView(R.id.imv_notify)
    ImageView imv_notify;

    @BindView(R.id.layout_circle_layout)
    RelativeLayout layout_circle_layout;

    private IPublishFeedPresenter presenter;
    private RecommendCircleAdapter adapter;
    private List<RecommendCirclesEntity> datas = new ArrayList<>();

    private static final int REQUEST_CODE_PICK_IMAGE = 0x01;
    private static final int REQUEST_CODE_TAKE_PHOTO = 0x02;
    private Uri take_photo_uri;
    private String cature_url = "";
    private MaterialDialog progressDialog;
    private String pic_url = "";
    private String circle_hash = "";
    private int page_index = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_create_feed;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        presenter = new PublishFeedPresenterImpl(this);
        adapter = new RecommendCircleAdapter(this, datas);
        recommend_list_view.setAdapter(adapter);
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                App.GetInstance().finishActivity(CreateFeedActivity.this);
            }
        });
        edt_circle_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    layout_feed_time_line.setVisibility(View.GONE);
                    line_horizontal3.setVisibility(View.GONE);
//                    edt_title.setVisibility(View.VISIBLE);
                    layout_recommend.setVisibility(View.GONE);
                } else {
                    layout_feed_time_line.setVisibility(View.VISIBLE);
                    line_horizontal3.setVisibility(View.VISIBLE);
                    if (edt_circle_name.hasFocus()) {
                        presenter.queryRecommandCircles(editable.toString());
                    }
                }
            }
        });
        imv_notify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MaterialDialog dialog = new MaterialDialog.Builder(CreateFeedActivity.this).content("圈子是一个私密交流场所，在这没人知道你的真实身份。加入圈子是神秘的，需要圈内人邀请。圈子内的信息24小时自动删除，拒绝挖坟。\n快创建你的圈子吧。").positiveText("关闭").onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }).build();
                dialog.show();
            }
        });
        publish_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (page_index == 0) {
                    if (TextUtils.isEmpty(edt_title.getText().toString())) {
                        new MaterialDialog.Builder(CreateFeedActivity.this).title("提示").positiveText("确定").content("请输入标题").onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        }).show();
                        return;
                    } else {
                        publish_tv.setText("提交");
                        page_index = 1;
                        edt_title.setVisibility(View.GONE);
                        layout_circle_layout.setVisibility(View.VISIBLE);
                        edt_more.setVisibility(View.GONE);
                        imv_feed_image.setVisibility(View.GONE);
                        layout_vote_option.setVisibility(View.VISIBLE);
                        layout_vs.setVisibility(View.VISIBLE);
                    }
                } else if (page_index == 1) {
                    if (checkValidate()) {
                        String title = edt_title.getText().toString();
                        String desc = edt_more.getText().toString();
                        String circle_name = edt_circle_name.getText().toString();
                        String circle_has = circle_hash;
                        String last_hour = "";
                        if (TextUtils.isEmpty(circle_name)) {
                            last_hour = "";
                        } else {
                            if (radio_btn_8hour.isChecked()) {
                                last_hour = "8";
                            } else {
                                last_hour = "24";
                            }
                        }
                        String pic_url_upload = pic_url;
                        String left = "";
                        if (TextUtils.isEmpty(edt_default_positive.getText().toString())) {
                            left = "赞同";
                        } else {
                            left = edt_default_positive.getText().toString();
                        }
                        String right = "";
                        if (TextUtils.isEmpty(edt_default_negative.getText().toString())) {
                            right = "反对";
                        } else {
                            right = edt_default_negative.getText().toString();
                        }
                        presenter.CreateFeed(title, desc, pic_url_upload, left, right, circle_name, circle_has, last_hour);
                    }
                }
            }
        });

        imv_feed_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MaterialDialog.Builder(CreateFeedActivity.this)
                        .title("选择图片")
                        .items("相册选择", "拍摄照片")
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                if (position == 0) {
                                    Intent intent = new Intent(Intent.ACTION_PICK);
                                    intent.setType("image/*");
                                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                                } else if (position == 1) {
                                    String savePath = "";
                                    // 判断是否挂载了SD卡
                                    String storageState = Environment
                                            .getExternalStorageState();
                                    if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                                        savePath = Environment
                                                .getExternalStorageDirectory()
                                                .getAbsolutePath()
                                                + Constants.IMAGE_URL;// 存放照片的文件夹
                                        File savedir = new File(savePath);
                                        if (!savedir.exists()) {
                                            savedir.mkdirs();
                                        }
                                    } else {
                                        Toast.makeText(getApplicationContext(), "无法保存照片，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                                    String fileName = "voute_" + timeStamp + ".jpg";// 照片命名
                                    File out = new File(savePath, fileName);
                                    Uri uri = Uri.fromFile(out);
                                    cature_url = savePath + fileName;// 该照片的绝对路径
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                    startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
                                }
                            }
                        })
                        .show();
            }
        });

        //监听Title设置右上角发布按钮的颜色
        edt_title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString();
                if (content.length() >= 5) {
                    publish_tv.setTextColor(Color.parseColor("#fe3768"));
                    publish_tv.setEnabled(true);
                } else {
                    publish_tv.setTextColor(Color.parseColor("#a0a0a0"));
                    publish_tv.setEnabled(false);
                }
            }
        });
    }

    @Override
    public void setupData() {

    }

    private boolean checkValidate() {
        MaterialDialog notice_dialog;
        if (TextUtils.isEmpty(edt_title.getText().toString())) {
            notice_dialog = new MaterialDialog.Builder(CreateFeedActivity.this).title("提示").positiveText("确认").cancelable(false).content("请输入标题").build();
            notice_dialog.show();
            return false;
        }
        if (edt_title.getText().toString().length() < 5) {
            notice_dialog = new MaterialDialog.Builder(CreateFeedActivity.this).title("提示").positiveText("确认").cancelable(false).content("标题字数至少5位").build();
            notice_dialog.show();
            return false;
        }
        if(TextUtils.isEmpty(edt_circle_name.getText().toString())){
            notice_dialog = new MaterialDialog.Builder(CreateFeedActivity.this).title("提示").positiveText("确认").cancelable(false).content("请输入圈子名字").build();
            notice_dialog.show();
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            startCropActivity(uri);
        }
        if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
            if (!new File(cature_url).exists()) {
                return;
            }
            startCropActivity(Uri.fromFile(new File(cature_url)));
        }
        if (requestCode == UCrop.REQUEST_CROP) {
            showLoading();
            Uri resultUri = UCrop.getOutput(data);
            File upload_file = FileUtils.getFileByUri(resultUri);
            RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
            Map<String, RequestBody> params = RetrofitUploadFileParameterBuilder.newBuilder()
                    .addParameter("ftype", "feed")
                    .addParameter("wsfile", upload_file)
                    .bulider();
            IUploadFileModel model = new UploadFileModelImpl();
            model.uploadImage("https://up.5miaoapp.com/job", params).compose(TransformUtils.<UploadImgResponseBean>defaultSchedulers()).subscribe(new CommonSubscriber<UploadImgResponseBean>() {
                @Override
                public void onSuccess(UploadImgResponseBean response) {
                    hideLoading();
                    pic_url = response.getData().getBaseurl() + "_600.jpg";
                    GlideUtils.getInstance().loadSimpleContextVitMap(CreateFeedActivity.this, pic_url, imv_feed_image);
                }

                @Override
                public void onFailure(BaseBean response) {
                    hideLoading();
                    pic_url = "";
                }
            });
        }
    }

    private void startCropActivity(@NonNull Uri uri) {
        String destinationFileName = ((new Date()).getTime() + "");
        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), destinationFileName + ".jpg")));
        uCrop = ucropConfig(uCrop);
        uCrop.start(CreateFeedActivity.this);
    }

    private UCrop ucropConfig(@NonNull UCrop uCrop) {
        uCrop = uCrop.withAspectRatio(16, 9);
        UCrop.Options options = new UCrop.Options();
        options.setHideBottomControls(false);
        return uCrop.withOptions(options);
    }

    @Override
    public void setRecommandCircles(RecommendCirclesBean response) {
        if (response.getData().getCircles().size() == 0) {
            circle_hash = "";
//            edt_title.setVisibility(View.VISIBLE);
            layout_recommend.setVisibility(View.GONE);
            adapter.clearDatas();
        } else {
            edt_title.setVisibility(View.GONE);
            layout_recommend.setVisibility(View.VISIBLE);
            adapter.setDatas(response.getData().getCircles());
        }
    }

    @Override
    public void createFeedSuccess(String feed_hash) {

        Intent intent = new Intent(this, FeedDetailInfoActivity.class);
        intent.putExtra("KEY_FROM_CREATE", true);
        intent.putExtra("KEY_FEED_HASH", feed_hash);
        startActivity(intent);
        App.GetInstance().finishActivity(this);
    }

    @Override
    public void showLoading() {
        if (progressDialog == null) {
            progressDialog = new MaterialDialog.Builder(this)
                    .progress(true, 0)
                    .title("提示")
                    .content("请等待...")
                    .autoDismiss(false)
                    .cancelable(true)
                    .build();
        }
        progressDialog.show();
    }

    @Override
    public void hideLoading() {
        progressDialog.dismiss();
    }

    @Override
    public void showError(String errMsg) {
        MaterialDialog notice_dialog = new MaterialDialog.Builder(CreateFeedActivity.this).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }

    public class RecommendCircleAdapter extends BaseAdapter {

        private List<RecommendCirclesEntity> circles = new ArrayList<>();
        private Context mContext;

        public RecommendCircleAdapter(Context c, List<RecommendCirclesEntity> sources) {
            mContext = c;
            if (sources != null) {
                circles.clear();
                circles.addAll(sources);
            }
        }

        public void setDatas(List<RecommendCirclesEntity> datas) {
            if (datas != null) {
                circles.clear();
                circles.addAll(datas);
                notifyDataSetChanged();
            }
        }

        public void clearDatas() {
            circles.clear();
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return circles.size();
        }

        @Override
        public Object getItem(int i) {
            return circles.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convert_view, ViewGroup viewGroup) {
            if (convert_view == null) {
                convert_view = View.inflate(mContext, R.layout.adapter_recommend_circles, null);
            }
            initViews(convert_view, i);
            return convert_view;
        }

        private void initViews(View convert_view, int position) {
            final RecommendCirclesEntity entity = circles.get(position);
            TextView tv_recommend_circle_name = (TextView) convert_view.findViewById(R.id.tv_recommend_circle_name);
            tv_recommend_circle_name.setText(entity.getCircle_name());
            convert_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    edt_default_positive.requestFocus();
                    edt_circle_name.setText(entity.getCircle_name());
//                    edt_title.setVisibility(View.VISIBLE);
                    layout_recommend.setVisibility(View.GONE);
                    circle_hash = entity.getHash();
                    adapter.clearDatas();
                }
            });
        }
    }
}
